package com.authine.cloudpivot.ext.util;

import com.authine.common.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;

@Slf4j
public class ExcelImportUtils {

    public static List<Map<String, Object>> bbcPreValidateImportByFixedOnInputStream(String sonSchemaCode, ByteArrayOutputStream copyTempStream, int sheetIndex) {
        // 读取文件内容
        List<List<Object>> dataList = ExcelUtils.readExcelSheetByInputStream(copyTempStream, sheetIndex);
        //解析数据
        return commonDeal(dataList,sonSchemaCode);
    }

    private static List<Map<String, Object>> commonDeal(List<List<Object>> dataList,String sonSchemaCode){
        List<Object> headerList = dataList.get(0);
        Map<Integer, String> column2code = new HashMap<>();
        //硬编码 获取导入列信息
        Map<String, String> columnMap = ExcelFixedCoding.getExcelColumnMap(sonSchemaCode);
        for (int m = 0; m < headerList.size(); m++) {
            String headName = headerList.get(m).toString();
            log.info("表下标:"+m + ";表字段名称:"+headName);
            if("导入结果提示".equals(headName)){
                continue;
            }
            boolean match = false;
            for (String key : columnMap.keySet()) {
                String value = columnMap.get(key);
                if (value.equals(headName.replace("*",""))) {
                    column2code.put(m, key);
                    match = true;
                    break;
                }
            }
            Assert.isTrue(match,headName+"模型对应列信息不存在");
        }
        List<Map<String, Object>> resultData = new ArrayList<>();
        for (int i = 1; i < dataList.size(); i++) {
            List<Object> row = dataList.get(i);
            Map<String, Object> data = new LinkedHashMap<>();
            if(CollectionUtils.isEmpty(row)){
                continue;
            }
            for (int j = 0; j < row.size(); j++) {
                if (StringUtils.isEmpty(row.get(j))) {
                    continue;
                }
                data.put(column2code.get(j), row.get(j).toString());
            }
            if (CollectionUtils.isEmpty(data)) {
                continue;
            }
            resultData.add(data);
        }
        return resultData;
    }

    /**
     * 导出数据文件名
     */
    private static final String IMPORT_ERROR_FILE_NAME = "import_erorr";

    public static File bbcDownloadErrorFiles(String[] schemaCodes, Map<String, List<Map<String, String>>> errorMap, Map<String, String> sheetMap, String masterSchemaCode) {
        String filePath = getDefaultTemplateFilePath(IMPORT_ERROR_FILE_NAME, masterSchemaCode);
        File file = new File(filePath);
        FileUtil.deleteFile(file);
        Workbook workbook = ExcelUtils.getNullWorkbook();
        for (int i = 0; i < schemaCodes.length; i++) {
            List<Map<String, String>> errorData = errorMap.get(schemaCodes[i]);
            String sheetName = sheetMap.get(schemaCodes[i]);
            LinkedHashMap<String, String> columnMap = ExcelFixedCoding.getExcelColumnMap(schemaCodes[i]);
            ExcelUtils.createSheet(workbook,sheetName);
            ExcelUtils.writeTitleWithDataToWorkbook2(workbook, errorData, columnMap,i);
        }
        ExcelUtils.writeWorkbookToFile(workbook, file);
        return file;
    }

    /**
     * 获取默认模板文件的路径
     *
     * @return
     */
    private static String getDefaultTemplateFilePath(String fileName, String schemaCode) {
        String name = fileName + "_" + schemaCode + "_" + ExcelUtils.FILE_FORMAT.format(new Date()) + "." + ExcelUtils.XLSX;
        String path = System.getProperty("user.home") + File.separator + "_cpv_temp" + File.separator + name;
        return path;
    }

}
